package com.tmxk.employee.servlet;

import com.alibaba.fastjson.JSONObject;
import com.tmxk.employee.pojo.entity.TSchedule;
import com.tmxk.employee.service.TScheduleService;
import com.tmxk.employee.service.impl.TScheduleServiceImpl;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 行程计划控制层
 */
@WebServlet(name = "TScheduleServlet",urlPatterns = {"/TScheduleServlet"})
public class TScheduleServlet extends HttpServlet {
    private Logger logger = Logger.getLogger(TScheduleServlet.class);
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置request、response字符编码格式,解决中文乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        //创建业务访问层对象
        TScheduleService tScheduleService = new TScheduleServiceImpl();
        Map<String,Object> map = new HashMap<>();
        String tripModeId = request.getParameter("tripModeId");
        // 强调 : 获取的前端的所有数据都是字符串(0,1,2...) , 框架 和 数据库会帮自动转换数值类型的字符串
        //判断是否查询出行方式, 0 / null 查询所有,反之带条件查询
        if(tripModeId!= null && !"0".equals(tripModeId)){
            map.put("tripModeId", tripModeId );
        }
        List<TSchedule> tSchedules = tScheduleService.queryAllSchedule(map);

        logger.info("tSchedules>:" + tSchedules);
        // 将 tSchedules 集合数据转换成json数据格式
        // 提供了fastjson jar包快速转换, fastjson 低版本存在安全漏洞
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("tSchedules" , tSchedules);
        logger.info("tSchedules转换成json格式数据:" + jsonObject);
        // 通过response将后端数据响应给前端
        PrintWriter out = response.getWriter();
        out.println(jsonObject);
    }
}
